import Fly from 'flyio/dist/npm/wx'
const fly = new Fly()
import md5 from '@/js_sdk/md5.js'
import store from '@/store/index.js'
var util = require('./uuid.js');
import { Foundation } from '@/utils'
const host = "https://www.morekaba.com"
// const host = "http://www.2i623x9469.zicp.vip/"
// const host = "http://192.168.1.106:8082/"
let access_token = uni.getStorageSync('userInfo').access_token
// console.log('token is===',access_token)
const config = "dev"
//添加请求拦截器
fly.interceptors.request.use((request) => {
  wx.showLoading({
    title: "加载中",
    mask:true
  });
  request.headers = {
    "X-Tag": "flyio",
    'content-type': 'application/json'
  };
  // if(request.body!={} && request.body){
	request.body && Object.keys(request.body).forEach((val) => {
	  if(request.body[val] === ""){
	    delete request.body[val]
	  }
	})  
  // }
  
  
  if(request.needToken){
	if(config=== 'dev'){
		request.body = {
		  ...request.body
		} 
		request.headers = {
		  'Authorization': access_token?access_token:wx.getStorageSync('token')
		  // 'Authorization': access_token
		}; 
	}else{
		
		const uid = wx.getStorageSync('userInfo').id
		const nonce = randomString(6)
		const timestamp = parseInt(new Date().getTime() / 1000)
		// console.log('access_token=====',access_token)
		const sign = md5(uid + 'Ozv68b' + '1589975511' + access_token)
		// const sign = md5('16' + '3IIN0M' + '1539253041' + 'eyJhbGciOiJIUzUxMiJ9.eyJzZWxmT3BlcmF0ZWQiOjAsInN1YiI6IkNMRVJLIiwicm9sZSI6IlNVUEVSX1NFTExFUiIsImZvdW5kZXIiOm51bGwsInJvbGVzIjpbIkJVWUVSIiwiU0VMTEVSIiwiQ0xFUksiXSwic2VsbGVyTmFtZSI6Iumjn-WTgemFkuawtCIsImNsZXJrSWQiOjQsInV1aWQiOm51bGwsInVpZCI6MTYsInNlbGxlcklkIjoxNSwiY2xlcmtOYW1lIjoiZm9vZCIsImV4cCI6MTUzOTI1NDg0MCwidXNlcm5hbWUiOiJmb29kIn0.rHlV4mfV04YiON2TandK1geRXSVmKKRAn89iAWHKNR_wuaqZC4oz8qjKusgWudCi-9ul8OwZnqzmpvh_W5pPhA')
		console.log('sign',sign)
		const uuid = wx.getStorageSync('uuid')
		// console.log('uuid============',uuid)
		// const _params = { uid, nonce, timestamp, sign }
		const _params = { uid, nonce:'Ozv68b', timestamp:'1589975511', sign }
		request.body = {
			...request.body,
		}
		request.params = {
			..._params
		}
		request.headers = {
		  uuid
		}; 
	}
	fly.unlock();//解锁请求
	return request;
  }
}, (error, promise) => {
	promise.reject(error)
});

//添加响应拦截器
fly.interceptors.response.use(
  (response) => {
    wx.hideLoading();
    return response.data;//请求成功之后将返回值返回
  },
  (err, promise) => {
	  // console.log("err is=====>", err)
	  let uuid_old = uni.getStorageSync('uuid') || ''
	  let uuid_oold = uuid_old
	  let shop_id_old = uni.getStorageSync('shop_id')
	  let izShow = true
      wx.hideLoading();
      let msg = '';
      if (err.status === 0) {
        msg = '网络连接异常'
      } else if (err.status === 1) {
        msg = '网络连接超时'
      } else if (err.status === 401) {
        msg = '用户未登录'
      } else if (err.status === 403) {
        // msg = '登录已失效'
		// wx.clearStorageSync()
		izShow = false
		uni.clearStorageSync()
		uni.setStorageSync('shop_id',shop_id_old)
		wx.navigateTo({
		  url: '../login/login'
		});
      }else {
        if (err.response.data.message) {
			if(err.response.data.code ==='150'){
				izShow = false
				wx.hideToast()
			}else{
				msg = err.response.data.message
			}
			// else if(err.response.data.code ==='002'){
			// 	izShow = false
			// 	uni.clearStorageSync()
			// 	uni.setStorageSync('shop_id',shop_id_old)
			// 	wx.navigateTo({
			// 	  url: '../login/login'
			// 	});
			// }
        } else {
          msg = '请求数据失败,请稍后再试'
        }
      }
	  if(izShow){
		wx.showToast({
		    title: msg,
		    icon: 'none',
		    duration: 2000
		})
	  }else{
		  wx.hideToast()
	  }
      return promise.resolve(err)
    }
);
//设置超时
fly.config.timeout = 30000;
fly.config.baseURL = host;

export default fly;
export function randomString(length = 32) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  const maxPos = chars.length
  let _string = ''
  for (let i = 0; i < length; i++) {
    _string += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return _string
}